/*
 * Function test of qtsm_lib_api using glib framework
 *
 * Copyright (c) Huawei Technologies Co., Ltd. 2022. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0.
 */
#include "gtest_qtsm_lib_comm.h"

static comm_req g_qtsm_get_att_reqs[] = {
    /* data_len: boundary value */
    {
        .reqmsg = {
            .type = ATTESTATION,
            .qtsm_message_req_u = {
                .attestation = {
                    .user_data_len = QTSM_USER_DATA_MAX_SIZE,
                    .user_data = (uint8_t[QTSM_USER_DATA_MAX_SIZE]){0x01, 0x23, 0x45},
                    .nonce_len = QTSM_NONCE_MAX_SIZE,
                    .nonce = (uint8_t[QTSM_NONCE_MAX_SIZE]){0x01, 0x23, 0x45},
                    .pubkey_len = QTSM_PUBLIC_KEY_MAX_SIZE,
                    .pubkey = (uint8_t[QTSM_PUBLIC_KEY_MAX_SIZE]){0x01, 0x23, 0x45},
                }
            }
        },
        .resmsg = {
            .type = ATTESTATION,
            .qtsm_message_res_u = {
                .attestation = { 0 }
            }
        }
    }
};

void gtest_qtsm_get_attestation(const void *qtsm_dev_fd)
{
    struct attestation_document *cur_doc = NULL;
    uint32_t doc_cose_len = sizeof(struct attestation_document);
    uint8_t *doc_cose = NULL;
    int rc;
    unsigned int i;

    for (i = 0; i < ARRAY_SIZE(g_qtsm_get_att_reqs); i++) {
        cur_doc = qtsm_new_doc();
        g_assert_nonnull(cur_doc);
        doc_cose = g_malloc0(doc_cose_len);
        g_assert_nonnull(doc_cose);

        /* test qtsm_get_attestation api */
        rc = qtsm_get_attestation(*(int *)qtsm_dev_fd,
            g_qtsm_get_att_reqs[i].reqmsg.qtsm_message_req_u.attestation.user_data,
            g_qtsm_get_att_reqs[i].reqmsg.qtsm_message_req_u.attestation.user_data_len,
            g_qtsm_get_att_reqs[i].reqmsg.qtsm_message_req_u.attestation.nonce,
            g_qtsm_get_att_reqs[i].reqmsg.qtsm_message_req_u.attestation.nonce_len,
            g_qtsm_get_att_reqs[i].reqmsg.qtsm_message_req_u.attestation.pubkey,
            g_qtsm_get_att_reqs[i].reqmsg.qtsm_message_req_u.attestation.pubkey_len,
            doc_cose, &doc_cose_len);

        if (g_qtsm_get_att_reqs[i].resmsg.type == ERROR_CODE) {
            /* check error code */
            g_assert_cmpint(rc, ==,
                g_qtsm_get_att_reqs[i].resmsg.qtsm_message_res_u.error_num);
        } else {
            /* check ret value */
            g_assert_cmpint(rc, ==, NO_ERROR);
            rc = verify_parse_cboren_doc(doc_cose, doc_cose_len, cur_doc);
            g_assert_cmpint(rc, ==, NO_ERROR);
        }

        g_free(doc_cose);
        qtsm_free_doc(&cur_doc);
        g_assert_null(cur_doc);
    }
}
